package com.xsj.controller;

import cn.hutool.core.util.IdUtil;
import com.alipay.api.internal.util.AlipaySignature;
import com.xsj.config.AlipayConfig;
import com.pll.dto.ResponseDto;
import com.xsj.vo.AliPay;
import com.xsj.service.AlipayService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName AliPayController
 * @Description 阿里沙箱支付，包含支付减扣功能
 * @Author 小鹿
 * @Date 2025/6/24 10:32
 */

@Tag(name = "阿里云支付")
@RestController
@RequestMapping("alipay")
@Transactional(rollbackFor = Exception.class)
@CrossOrigin
public class AliPayController {

    @Resource
    AlipayConfig aliPayConfig;

    @Resource
    private AlipayService alipayService;

    private static final String FORMAT ="JSON";

    private AliPay aliPays = new AliPay();
    @Operation(summary = "调用沙箱支付", description = "通过传入的用户id、金额等生成支付表单提交给阿里内部接口验签")
    @GetMapping("/pay") // &subject=xxx&traceNo=xxx&totalAmount=xxx
    public void pay(@RequestParam("userId") Integer userId,
                    @RequestParam("amount") String amount,
                    @RequestParam("traceNo") String traceNo,
                    @RequestParam("subject") String subject,
                    HttpServletResponse httpResponse) {
        System.out.println("接收到的请求参数: " + userId+amount+traceNo+subject);
        AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getGatewayUrl(), aliPayConfig.getAppId(),
                aliPayConfig.getMerchantPrivateKey(), FORMAT, aliPayConfig.getCharset(), aliPayConfig.getAlipayPublicKey(), aliPayConfig.getSignType());
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
//        随机订单号 通过糊涂工具的雪花算法
        long uuid = IdUtil.getSnowflake(userId).nextId();
//        aliPay.setTraceNo(uuid.toString());
//        赋值给全局对象aliPays 让post请求中可以使用
        aliPays.setUserId(userId);
        aliPays.setAmount(amount);
        aliPays.setTraceNo(uuid);
        aliPays.setSubject(subject);
//        返回前端页面
        request.setReturnUrl(aliPayConfig.getReturnUrl());

        request.setBizContent("{\"out_trade_no\":\"" + uuid + "\","
                + "\"total_amount\":\"" + amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            System.err.println("生成支付宝支付表单出错: " + e.getMessage());
            e.printStackTrace();
        }
        try {
            httpResponse.setContentType("text/html;charset=" + aliPayConfig.getCharset());
            // 直接将完整的表单html输出到页面
            httpResponse.getWriter().write(form);
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        } catch (IOException e) {
            System.err.println("输出支付表单 HTML 出错: " + e.getMessage());
            e.printStackTrace();
        }
    }

    @Operation(summary = "进行验签", description = "验签通过执行新增订单操作")
    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
//                显示所有request参数
                System.out.println(name + " = " + request.getParameter(name));
            }
//            订单号
            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");

            // 支付宝官方提供的验签方法
            boolean signatureVerification = AlipaySignature.rsaCheckV1(
                    params,
                    aliPayConfig.getAlipayPublicKey(),
                    aliPayConfig.getCharset(),
                    aliPayConfig.getSignType());
            System.out.println(signatureVerification);

            // 支付宝验签
            if (signatureVerification) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 更新订单为已支付 并进行三层curd操作
                System.out.println("aliPay参数为："+aliPays);
                ResponseDto recharge = alipayService.pay(aliPays);
                System.out.println(recharge);
            }
        }
        return "success";
    }
}